package shop.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import shop.gateway.config.GatewaySecurityConfig;

@Component
@Slf4j
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private final GatewaySecurityConfig securityConfig;

    private final  String TOKEN_HEADER = "Authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();

        // 1. 检查是否是放行路径
        if (isExcludePath(path)) {
            return chain.filter(exchange);
        }


        // 2. 获取token
        String token = getToken(exchange.getRequest());
        if (!StringUtils.hasLength(token)) {
            throw new RuntimeException("token is null");
        }



        // 网关转发请求，将数据添加到下一次请求中
        ServerHttpRequest.Builder mutate = exchange.getRequest().mutate();
        mutate.header(TOKEN_HEADER, token);

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    @Override
    public int getOrder() {
        return -100;
    }

    // 判断是否是放行路径
    private boolean isExcludePath(String path) {
        return securityConfig.getExcludePaths().stream()
                .anyMatch(excludePath ->
                        path.startsWith(excludePath) ||
                                path.matches(excludePath.replace("/**", ".*"))
                );
    }

    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TOKEN_HEADER);
        if (StringUtils.hasLength(token) && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return token;
    }

}
